package org.sith.taskrunner.gwt.server.filters;

import org.apache.commons.codec.binary.Base64;
import org.sith.taskrunner.api.user.User;
import org.sith.taskrunner.ejb.UserThreadKeeper;
import org.sith.taskrunner.ejb.services.UserManagerService;

import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class AuthFilter implements Filter {


    private static final String USER = "USER";

    @EJB(name = "UserManagerServiceEJB")
    private UserManagerService userManagerService;

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {


        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(USER);
        if (user != null) {
            UserThreadKeeper.setThreadUser(user);
            chain.doFilter(req, resp);
            return;
        }

        String header = request.getHeader("Authorization");
        if (header != null) {

            String loginAndPasswordEncoded = header.replace("Basic ", "");

            byte[] bytes = Base64.decodeBase64(loginAndPasswordEncoded.getBytes());

            String decodedLoginAndPassword = new String(bytes, "UTF-8");

            String[] split = decodedLoginAndPassword.split(":");
            String login;
            String password;
            if (split.length == 2) {
                login = split[0];
                password = split[1];
                user = userManagerService.getUserByNameAndPassword(login, password);
                if (user != null) {
                    session.setAttribute(USER, user);
                    UserThreadKeeper.setThreadUser(user);
                    chain.doFilter(req, resp);
                    return;
                }
            }
        }

        response.setHeader("WWW-Authenticate", "Basic realm=\"taskRunnerRealm\"");
        response.sendError(401);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
